package com.cjh.mybatis10.scriping.defaults;

import com.cjh.mybatis10.bulider.SqlSourceBuilder;
import com.cjh.mybatis10.mapping.BoundSql;
import com.cjh.mybatis10.mapping.SqlSource;
import com.cjh.mybatis10.scriping.xmltags.DynamicContext;
import com.cjh.mybatis10.scriping.xmltags.SqlNode;
import com.cjh.mybatis10.session.Configuration;

import java.util.HashMap;

/**
 * @Descripton  原始SQL源码，比 DynamicSqlSource 动态SQL处理快
 * @Author cjh
 * @Date 2023/6/12 14:43
 */
public class RawSqlSource implements SqlSource {
    private final SqlSource sqlSource;
    public RawSqlSource(Configuration configuration, SqlNode rootSqlNode, Class<?> parameterType){
        this(configuration,getSql(configuration,rootSqlNode),parameterType);
    }

    public RawSqlSource(Configuration configuration,String sql,Class<?> parameterType){
        SqlSourceBuilder sqlSourceParser = new SqlSourceBuilder(configuration);
        Class<?> clazz = parameterType == null? Object.class:parameterType;
        sqlSource = sqlSourceParser.parse(sql,clazz,new HashMap<>());
    }

    @Override
    public BoundSql getBoundSql(Object parameterObject) {
        return sqlSource.getBoundSql(parameterObject);
    }

    private static String getSql(Configuration configuration,SqlNode rootSqlNode){
        DynamicContext dynamicContext = new DynamicContext(configuration, null);
        rootSqlNode.apply(dynamicContext);
        return dynamicContext.getSql();

    }
}
